﻿using System;
using System.Drawing;
using System.IO;

namespace DoNetTool.Common
{
    /// <summary>
    /// 图片工具类
    /// </summary>
    public class PictureTool
    {
        /// <summary>
        /// 生成照片
        /// </summary>
        /// <param name="data">图片base64流</param>
        /// <param name="savePath">保存路径</param>
        public static bool Photograph(string data, string savePath)
        {
            try
            {
                string strbase64 = data.Substring(data.IndexOf(',') + 1);
                strbase64 = strbase64.Trim('\0');
                //Log.Debug("strbase64:" + strbase64);
                byte[] arr = Convert.FromBase64String(strbase64);
                using (MemoryStream ms = new MemoryStream(arr))
                {
                    Bitmap bmp = new Bitmap(ms);
                    //if (!Directory.Exists(filePath))
                    //    Log.Debug("没有Directory");
                    //Directory.CreateDirectory(filePath);
                    //新建第二个bitmap类型的bmp2变量。
                    Bitmap bmp2 = new Bitmap(bmp, bmp.Width, bmp.Height);
                    //将第一个bmp拷贝到bmp2中
                    Graphics draw = Graphics.FromImage(bmp2);
                    draw.DrawImage(bmp, 0, 0);
                    draw.Dispose();
                    bmp2.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    //bmp.Save("test.bmp", ImageFormat.Bmp);
                    //bmp.Save("test.gif", ImageFormat.Gif);
                    //bmp.Save("test.png", ImageFormat.Png);
                    ms.Close();
                    //return filePath + fileName;
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
